package com.yxy.chatserver.service.impl;

import com.yxy.chatserver.constant.MessageStatusConstant;
import com.yxy.chatserver.domain.po.*;
import com.yxy.chatserver.mapper.MessageContentsMapper;
import com.yxy.chatserver.mapper.MessageMapper;
import com.yxy.chatserver.mapper.UserMapper;
import com.yxy.chatserver.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.yxy.chatserver.constant.MessageTypeConstant.NEW_FRIEND_REQUEST;

/**
 * 消息服务实现类
 * 提供消息的存储、检索等功能
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    private static final Random random = new Random();

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageContentsMapper messageContentsMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 保存消息
     *
     * @param baseMessage 要存储的消息
     */
    @Override
    public void saveMessage(BaseMessage baseMessage) {
        baseMessage.setId(generateMessageId());
        // 保存到信息主表
        messageMapper.save(baseMessage);
        // 根据消息类型保存扩展字段
        List<MessageContents> list = new ArrayList<>();
        if (baseMessage instanceof FriendMessage) {
            FriendMessage msg = (FriendMessage) baseMessage;
            list.add(createField(msg.getId(), "note", msg.getNote()));
            list.add(createField(msg.getId(), "requestStatus", msg.getRequestStatus()));
        }
        messageContentsMapper.saveFieldBatch(list);
    }

    /**
     * 创建消息扩展字段
     * @param id
     * @param fieldKey
     * @param fieldValue
     * @return
     */
    private MessageContents createField(String id, String fieldKey, String fieldValue) {
        MessageContents messageContents = new MessageContents();
        messageContents.setMessageId(id);
        messageContents.setFieldKey(fieldKey);
        messageContents.setFieldValue(fieldValue);
        return messageContents;
    }

    /**
     * 获取用户的未读消息
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<BaseMessage> getUnreadMessages(String userId) {
        List<BaseMessage> unreadMessagesList = new ArrayList<>();
        // 获取用户未读消息（主表和扩展字段表）（已发送未接收）
        List<BaseMessage> unreadMessages = messageMapper.getUnreadMessages(userId);
        for(BaseMessage message: unreadMessages){
            // 根据消息id查询消息内容
            List<MessageContents> messageContents = messageContentsMapper.getMessageContentsByMessageId(message.getId());
            BaseMessage baseMessage = createMessageByType(message.getType(), message, messageContents);
            // 获取发送者和接收者的缓存字段
            User fromUser = userMapper.getById(message.getFromUserId());
            User toUser = userMapper.getById(message.getToUserId());
            baseMessage.setFromUserNickname(fromUser.getNickname());
            baseMessage.setFromUserAvatar(fromUser.getAvatar());
            baseMessage.setToUserNickname(toUser.getNickname());
            baseMessage.setToUserAvatar(toUser.getAvatar());
            unreadMessagesList.add(baseMessage);
        }
        return unreadMessagesList;
    }

    /**
     * 根据消息类型创建消息对象
     * @param type
     * @param message
     * @param messageContents
     * @return
     */
    public BaseMessage createMessageByType(String type, BaseMessage message, List<MessageContents> messageContents) {
        switch (type){
            case NEW_FRIEND_REQUEST:
                FriendMessage friendMessage = new FriendMessage();
                setBaseMessageFields(friendMessage, message);
                messageContents.forEach(messageContent -> {
                    switch (messageContent.getFieldKey()){
                        case "note":
                            friendMessage.setNote(messageContent.getFieldValue());
                            break;
                        case "requestStatus":
                            friendMessage.setRequestStatus(messageContent.getFieldValue());
                            break;
                    }
                });
                return friendMessage;
            default:
                log.warn("不支持的消息类型：{}", type);
                return null;
        }
    }

    /**
     * 设置消息基础字段
     * @param friendMessage
     * @param message
     */
    private void setBaseMessageFields(BaseMessage target, BaseMessage source) {
        target.setId(source.getId());
        target.setFriendId(source.getFriendId());
        target.setFromUserId(source.getFromUserId());
        target.setToUserId(source.getToUserId());
        target.setType(source.getType());
        target.setSendTime(source.getSendTime());
        target.setStatus(source.getStatus());
    }

    /**
     * 标记消息为已读
     *
     * @param messageId 消息ID
     */
    @Override
    public void markMessageAsRead(String messageId) {
        messageMapper.updateStatusById(messageId, MessageStatusConstant.RECEIVED);
    }

    /**
     * 批量标记所有消息为已读
     *
     * @param userId 用户ID
     */
    @Override
    public void markAllMessagesAsRead(String userId) {
    }

    /**
     * 获取聊天记录
     *
     * @param userId1  用户ID1
     * @param userId2  用户ID2
     * @param page     页码
     * @param pageSize 每页数量
     * @return 聊天记录列表
     */
    @Override
    public List<BaseMessage> getChatHistory(String userId1, String userId2, int page, int pageSize) {
        return null;
    }

    /**
     * 生成消息ID
     *
     * @return 消息ID
     */
    private String generateMessageId() {
        return "msg_" + System.currentTimeMillis() + "_" + random.nextInt(10000);
    }
}